<?php


namespace App\Task\OperationLog;


use App\Task\MongoTask;

class AdminTask extends MongoTask
{
    protected $db;

    protected $collection;

    public function __construct()
    {
        $this->db = config('mongodb.default.db');
        $this->collection = 'admin_opera';
    }

    /**
     * @param $data
     * @return int|null
     */
    public function setLogData($data)
    {
        $log = [
            'user_id' => $data->id,
            'user_name' => $data->username,
            'event' => $data->event,
            'arguments' => $data->arguments,
            'created_at' => date('Y-m-d H:i:s')
        ];

       return $this->insert($this->db.'.'.$this->collection.$data->id,$log);
    }

    /**
     * 获取总数
     * @param int $id
     * @param array $where
     * @return int
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getCount(int $id,$where = [])
    {
        $filter = ['count' => $this->collection.$id];
        if (!empty($where)){
            array_push($filter,$where);
        }
        $result = $this->command($this->db,$filter);

        $cnt = 0;
        if ($result) {
            $cnt = $result[0]->n;
        }
        return $cnt;
    }

    /**
     * 分页
     * @param int $id
     * @param array $where
     * @param array $option
     * @param int $page
     * @param int $limit
     * @return mixed
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function page(int $id,$where=[],$option=[],$page=1,$limit=15)
    {
        $count = $this->getCount($id,$where);
        $lastPage = ceil($count/$limit);
        if ($page > $lastPage) {
            $page = $lastPage > 0 ? $lastPage : 1;
        }elseif($page < 1) {
            $page = 1;
        }
        $skip = ($page-1)*$limit;
        $options = [
            'skip' => $skip,
            'limit' => $limit,
        ];
        array_merge($options,$option);
        $data['data'] = $this->query($this->db.'.'.$this->collection.$id,$where,$options);
        $data['count'] = $count; //总数
        $data['page'] = (int)$page;  //当前页
        $data['per_page'] = $limit; //显示条数
        return $data;
    }

}